package com.wing.order.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.CodeUtil;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.Result;
import com.wing.config.BaseDataInit;
import com.wing.enterprise.feign.EnterpriseClient;
import com.wing.enterprise.invoicing.model.entity.TransportCompany;
import com.wing.enterprise.product.model.entity.CabInventoryProduct;
import com.wing.enterprise.product.model.entity.CabInventoryProductRecord;
import com.wing.enterprise.product.model.entity.ProductPackLabelOut;
import com.wing.enterprise.product.model.request.CabInventoryProductForm;
import com.wing.enterprise.product.model.request.ProductPackLabelDetailForm;
import com.wing.enterprise.product.model.request.ProductPackLabelForm;
import com.wing.enterprise.product.model.response.ProductDetailVO;
import com.wing.enterprise.product.model.response.ProductPackLabelVO;
import com.wing.enterprise.product.model.response.ProductTypeVO;
import com.wing.enterprise.product.model.response.ProductVO;
import com.wing.order.dao.*;
import com.wing.order.model.entity.*;
import com.wing.order.model.request.InventoryInoutJobForm;
import com.wing.order.model.request.InventoryJobForm;
import com.wing.order.model.response.*;
import com.wing.platform.feign.PlatformClient;
import com.wing.platform.storage.request.InventoryInoutPlanDetailForm;
import com.wing.platform.storage.request.InventoryInoutPlanForm;
import com.wing.product.model.entity.ProductPackLabel;
import com.wing.product.service.ProductDetailService;
import com.wing.product.service.ProductPackLabelService;
import com.wing.user.feign.UserClient;
import com.wing.user.model.response.UserVO;
import com.wing.warehouse.dao.BoxLabelDao;
import com.wing.warehouse.dao.PalletBoxListDao;
import com.wing.warehouse.dao.WarehouseDao;
import com.wing.warehouse.model.entity.BoxLabel;
import com.wing.warehouse.model.entity.WarehouseInventoryType;
import com.wing.warehouse.model.response.PalletBoxListVO;
import com.wing.warehouse.model.response.WarehouseVO;
import com.wing.warehouse.service.BoxLabelService;
import com.wing.warehouse.service.WarehouseAreaService;
import com.wing.warehouse.service.WarehouseInventoryTypeService;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 出/入库作业单记录-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class InventoryInoutJobServiceImpl extends ServiceImpl<InventoryInoutJobDao, InventoryInoutJob> implements InventoryInoutJobService {
    @Value("${platform.gatewayUrl}")
    private String gatewayUrl;
    @Autowired
    private InventoryInoutService inventoryInoutService;
    @Autowired
    private InventoryJobProductDao inventoryJobProductDao;
    @Autowired
    private DynamicDao dynamicDao;
    @Autowired
    private InventoryJobLabelDao inventoryJobLabelDao;
    @Autowired
    private InventoryInoutJobDao inventoryInoutJobDao;
    @Autowired
    private InventoryJobDao inventoryJobDao;
    @Autowired
    private EnterpriseClient enterpriseClient;
    @Autowired
    private InventoryOutPlanDao inventoryOutPlanDao;
    @Autowired
    private InventoryOutPlanDetailService inventoryOutPlanDetailService;
    @Autowired
    private InventoryOutPlanDetailDao inventoryOutPlanDetailDao;
    @Autowired
    private WarehouseDao warehouseDao;
    @Autowired
    private OrderDeliveryDetailService orderDeliveryDetailService;
    @Autowired
    private OrderDistributionLabelService orderDistributionLabelService;
    @Autowired
    private PlatformClient platformClient;
    @Autowired
    private  WarehouseInventoryTypeService warehouseInventoryTypeService;
    @Autowired
    private WarehouseAreaService warehouseAreaService;
    @Autowired
    private BoxLabelService boxLabelService;
    @Autowired
    private InventoryInoutDao inventoryInoutDao;
    @Autowired
    private UserClient userClient;
    @Autowired
    private PalletBoxListDao palletBoxListDao;
    @Autowired
    private InventoryInoutDetailDao inventoryInoutDetailDao;
    @Autowired
    private BoxLabelDao boxLabelDao;
    @Autowired
    private  InventoryJobLabelService inventoryJobLabelService;
    @Autowired
    private ProductDetailService productDetailService;
    @Autowired
    private InventoryJobSignProductDetailDao inventoryJobSignProductDetailDao;
    @Autowired
    private PurchaseService purchaseService;
    @Autowired
    private ProductPackLabelService productPackLabelService;
    @Autowired
    private CabInventoryProductService cabInventoryProductService;
    @Autowired
    private CabInventoryProductRecordService inventoryProductRecordService;

    @Override
    public int add(InventoryInoutJobForm inventoryInoutJobForm) {

        //校验

        InventoryInoutJob inventoryInoutJob = new InventoryInoutJob();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(InventoryInoutJob.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(inventoryInoutJobForm, inventoryInoutJob, copyOptions);

        return baseMapper.insert(inventoryInoutJob);
    }

    @Override
    public List<InventoryInoutJobVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<InventoryInoutJobVO> pageList4app(Page page, Map<String, Object> params) {
        List<InventoryInoutJobVO> list = baseMapper.list4app(page, params);
        for (int i=0;i<list.size();i++) {
            Map map = new HashMap();
            map.put("jobId",list.get(i).getId());
            list.get(i).setJobLabelList(inventoryJobLabelService.list4app(map));
        }
        page.setRecords(list);
        return page;
    }

    @Override
    public Page<InventoryInoutJobVO> pageList4loading(Page page, Map<String, Object> params) {
        List<InventoryInoutJobVO> list = baseMapper.list4loading(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public InventoryInoutJobVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Transactional
    @Override
    public JsonResult addInventoryInoutJob(Long planId, Long signStationId, String remark, Long signAmount, String productJson,String signStationName,Long boxId) {
        //入库作业单添加
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String today = format.format(new Date());
        InventoryInoutJob inventoryInoutJob = new InventoryInoutJob();
        InventoryInoutVO inoutVO = inventoryInoutService.get4appById(planId);
        Integer maxCode = dynamicDao.getDayMaxNo("ord_inventory_inout_job");
        String code = CodeUtil.getCode(maxCode);
        inventoryInoutJob.setSkuCode(inoutVO.getSkuCode());
        inventoryInoutJob.setCode(inoutVO.getCode() + code);
        inventoryInoutJob.setPlanCode(inoutVO.getCode());
        inventoryInoutJob.setPlanId(inoutVO.getId());
        inventoryInoutJob.setQuantity(signAmount);//包装码总签收数
        inventoryInoutJob.setSignStationId(signStationId);
        inventoryInoutJob.setSignStationName(signStationName);
        inventoryInoutJob.setRemark(remark);
        inventoryInoutJob.setInoutType(InventoryInoutJob.InoutType.valueOf("in"));
        inventoryInoutJob.setNo(Integer.valueOf(code));
        inventoryInoutJob.setDay(Integer.valueOf(today));
        //查询商品类型
        JsonResult<ProductDetailVO> jsonDetail = enterpriseClient.getProductDetailBySkuCode(inoutVO.getSkuCode());
        JsonResult<ProductVO> productVoJson = enterpriseClient.getProductById(jsonDetail.getData().getProductId());
        JsonResult<ProductTypeVO> typeJson = enterpriseClient.getProductTypeVoById(productVoJson.getData().getProductTypeId());
        inventoryInoutJob.setProductType(typeJson.getData().getName());
        inventoryInoutJob.setProductTypeId(typeJson.getData().getId());
        baseMapper.insert(inventoryInoutJob);
        //入库作业单的产品明细
        JSONArray jsonArray = JSONArray.parseArray(productJson);
        for (int i = 0; i < jsonArray.size(); i++) {
            InventoryJobProduct jobProduct = new InventoryJobProduct();
            InventoryJobLabel jobLabel = new InventoryJobLabel();
            JSONObject obj = (JSONObject) jsonArray.get(i);
            Long packLabeId = Long.parseLong(obj.getString("packLabeId"));
            String packLabeCode = obj.getString("packLabeCode");
            Long packId = Long.parseLong(obj.getString("packId"));
            String packName = obj.getString("packName");
            String skuCode = obj.getString("skuCode");
            String skuSpecCode = obj.getString("skuSpecCode");
            String unitName = obj.getString("unitName");
            Long unitId = Long.parseLong(obj.getString("unitId"));
            Long quantity = Long.parseLong(obj.getString("quantity"));
            if(i==0){
                jobProduct.setJobId(inventoryInoutJob.getId());
                jobProduct.setSkuCode(skuCode);
                jobProduct.setSkuSpecCode(skuSpecCode);
                jobProduct.setUnitId(unitId);
                jobProduct.setUnitName(unitName);
                jobProduct.setQuantity(signAmount);//包装码总签收数
                jobProduct.setPackId(packId);
                jobProduct.setPackName(packName);
                inventoryJobProductDao.insert(jobProduct);
            }
            jobLabel.setJobId(inventoryInoutJob.getId());
            jobLabel.setJobProductId(jobProduct.getId());
            jobLabel.setQuantity(quantity);
            jobLabel.setPackLabeCode(packLabeCode);
            jobLabel.setPackLabeId(packLabeId);
            jobLabel.setPlanId(inoutVO.getId());
            inventoryJobLabelDao.insert(jobLabel);
            //判断入库单包装条码的数量是否大于或等于入库计划的送料数
            Map<Integer, Object> inoutSumMap = inventoryInoutJobDao.getInventoryInoutSum(inoutVO.getId());
            Integer planSum = Integer.valueOf(inoutSumMap.get("planSum").toString());
            Integer total = Integer.valueOf(inoutSumMap.get("total").toString());
            InventoryInout inventoryInout = new InventoryInout();
            CopyOptions copyOptions = CopyOptions.create()
                    .setEditable(InventoryInout.class)
                    .setIgnoreError(true)
                    .setIgnoreNullValue(true);
            BeanUtil.copyProperties(inoutVO, inventoryInout, copyOptions);
            if(planSum >= total){
                inventoryInout.setStatus(InventoryInout.Status.storage);
                inventoryInoutService.updateById(inventoryInout);
            }
            //产品包装条码数量变化记录
            //查询包装码
            JsonResult<ProductPackLabelVO> packLabelJson = enterpriseClient.getProductPackLabelById(packLabeId);
            if (packLabelJson.getCode() == Result.Code.SUCCESS.getCode()) {
                //调用接口 extractPackLabel
                enterpriseClient.extractPackLabel(packLabeCode,quantity.intValue(),1);
            } else {
                throw new BusinessException("包装码数据不存在" + "packLabeId:" + packLabeId);
            }
            ProductPackLabelOut productPackLabelOut = new ProductPackLabelOut();
            productPackLabelOut.setQuantityCurrent(packLabelJson.getData().getQuantity());
            productPackLabelOut.setPackLabelId(packLabelJson.getData().getId());
            productPackLabelOut.setQuantityAfter((int) (packLabelJson.getData().getSurplusQuantity() - quantity.longValue()));
            productPackLabelOut.setQuantityOut((int) quantity.longValue());
            enterpriseClient.addProductPackLabelOut(productPackLabelOut);
            //增加库存和库存变动
            //查询是否有库存数据
            JsonResult<CabInventoryProduct> jsonInventory = enterpriseClient.getCabInventoryProductVOBySkuCode(skuCode);
            CabInventoryProduct cabInventory = jsonInventory.getData();

            CabInventoryProductForm cabInventoryProduct = new CabInventoryProductForm();
            CabInventoryProductRecord inventoryProductRecord = new CabInventoryProductRecord();
            if (cabInventory.getId() == null) {
                //区分是签收刀具入库还是生产入库
                if(inoutVO.getInoutTypeCode().equals("cutter")){
                    cabInventoryProduct.setType(CabInventoryProduct.Type.knife);
                }else{
                    cabInventoryProduct.setType(CabInventoryProduct.Type.make);
                }
                cabInventoryProduct.setPlanId(inoutVO.getId());
                cabInventoryProduct.setJobId(inventoryInoutJob.getId());
                cabInventoryProduct.setSkuCode(skuCode);
                cabInventoryProduct.setQuantity((int) quantity.longValue());
                enterpriseClient.addCabInventoryProduct(cabInventoryProduct);
                //库存变动记录的值
                JsonResult<CabInventoryProduct> json = enterpriseClient.getCabInventoryProductVOBySkuCode(skuCode);
                inventoryProductRecord.setInventoryProductId(json.getData().getId());
                inventoryProductRecord.setQuantityCurrent((int) quantity.longValue());
                inventoryProductRecord.setQuantityAfter((int) quantity.longValue());
            } else {
                //库存变动记录的值
                inventoryProductRecord.setInventoryProductId(cabInventory.getId());
                inventoryProductRecord.setQuantityCurrent(cabInventory.getQuantity());//当前库存
                inventoryProductRecord.setQuantityAfter(cabInventory.getQuantity() + (int) quantity.longValue());//变动后库存
                //库存变动
                cabInventory.setQuantity(cabInventory.getQuantity() + (int) quantity.longValue());
                enterpriseClient.updateCabInventoryProduct(cabInventory);
            }
            //库存变动记录
            inventoryProductRecord.setPlanId(inoutVO.getId());
            inventoryProductRecord.setJobId(inventoryInoutJob.getId());
            inventoryProductRecord.setSkuCode(skuCode);
            inventoryProductRecord.setType(CabInventoryProductRecord.Type.valueOf("in"));
            enterpriseClient.addCabInventoryProductRecord(inventoryProductRecord);
            //cabInventoryProductRecordDao.insert(inventoryProductRecord);

        }

        return JsonResult.success("操作成功");
    }

    @Override
    public IPage<InventoryInoutJobVO> getInventoryInoutJobPageList(InventoryInoutJob inventoryInoutJob, Integer page, Integer limit) {
        IPage<InventoryInoutJobVO> iPage = new Page<InventoryInoutJobVO>(page, limit);
        QueryWrapper<InventoryInoutJobVO> wrapper = new QueryWrapper<>();
        if (inventoryInoutJob.getPlanId() != null) {
            wrapper.eq("job.plan_id", inventoryInoutJob.getPlanId());
        }
        if (inventoryInoutJob.getWarehouseId() != null) {
            wrapper.eq("job.warehouse_id", inventoryInoutJob.getWarehouseId());
        }
        if (StringUtils.isNotBlank(inventoryInoutJob.getInoutTypeCode())) {
            wrapper.eq("job.inout_type_code", inventoryInoutJob.getInoutTypeCode());
        }

        if (StringUtils.isNotEmpty(inventoryInoutJob.getCode())) {
            wrapper.and(qw -> qw.like("job.code", inventoryInoutJob.getCode()));
        }
        if (StringUtils.isNotEmpty(inventoryInoutJob.getPlanCode())) {
            wrapper.and(qw -> qw.like("job.plan_code", inventoryInoutJob.getPlanCode()));
        }
        if (StringUtils.isNotEmpty(inventoryInoutJob.getSkuCode())) {
            wrapper.and(qw -> qw.like("jp.sku_code", inventoryInoutJob.getSkuCode()));
        }
        if (inventoryInoutJob.getStatus() != null) {
            wrapper.eq("job.status", InventoryInoutJob.Status.valueOf(inventoryInoutJob.getStatus().toString()));
        }
        wrapper.eq("job.inout_type", 1);
        wrapper.orderByDesc("job.create_time");
        inventoryInoutJobDao.getInventoryInoutJobPageList(iPage, wrapper);
        return iPage;
    }

    @Transactional
    @Override
    public void addOutInventoryInoutJob(InventoryJobForm inventoryJobForm) {
        Long enerpriseId=JwtUtils.getEnterpriseId();
        String enterrpriseCode=JwtUtils.getEnterpriseCode();
        String loginUsername = JwtUtils.getLoginUsername();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String today = format.format(new Date());
        //查询企业id
        String enterpriseId = dynamicDao.getEnterpriseId();
        //查询出库计划
        InventoryOutPlanVO outPlanVO = inventoryOutPlanDao.get4appById(inventoryJobForm.getPlanId());
        //出库作业单
        InventoryInoutJob inventoryInoutJob = new InventoryInoutJob();
        Integer maxCode = dynamicDao.getDayMaxNo("ord_inventory_inout_job");
        String code = CodeUtil.getCode(maxCode);
        inventoryInoutJob.setCode(outPlanVO.getCode() +today+ code);
        inventoryInoutJob.setPlanId(outPlanVO.getId());
        inventoryInoutJob.setPlanCode(outPlanVO.getCode());
        inventoryInoutJob.setInoutType(InventoryInoutJob.InoutType.out);
        inventoryInoutJob.setQuantity(inventoryJobForm.getQuantityOut());
        inventoryInoutJob.setRemark(inventoryJobForm.getRemark());
        inventoryInoutJob.setNo(Integer.valueOf(code));
        inventoryInoutJob.setDay(Integer.valueOf(today));
        inventoryInoutJobDao.insert(inventoryInoutJob);
        InventoryJob inventoryJob = new InventoryJob();
        inventoryJob.setPlanId(outPlanVO.getId());
        inventoryJob.setJobId(inventoryInoutJob.getId());
        inventoryJob.setInoutType(InventoryJob.InoutType.out);
        inventoryJob.setCustomerName(inventoryJobForm.getCustomerName());
        inventoryJob.setCustomerConcat(inventoryJobForm.getCustomerConcat());
        inventoryJob.setCustomerMoble(inventoryJobForm.getCustomerMoble());
        inventoryJob.setCarNo(inventoryJobForm.getCarNo());
        inventoryJob.setExpressCode(inventoryJobForm.getExpressCode());
        inventoryJob.setCompanyId(inventoryJobForm.getCompanyId());
        inventoryJob.setTransportType(inventoryJobForm.getTransportType());
        inventoryJob.setInWarehouseId(inventoryJobForm.getInWarehouseId());
        inventoryJobDao.insert(inventoryJob);
        //出库作业单的产品明细
        JSONArray jsonArray = JSONArray.parseArray(inventoryJobForm.getProductJson());
        for (int i = 0; i < jsonArray.size(); i++) {
            InventoryJobProduct jobProduct = new InventoryJobProduct();
            jobProduct.setJobId(inventoryInoutJob.getId());
            JSONObject obj = (JSONObject) jsonArray.get(i);
            Long id = Long.parseLong(obj.getString("id"));
            String skuCode = obj.getString("skuCode");
            String productName = obj.getString("productName");
            String skuPic = obj.getString("skuPic");
            String skuSpecCode = obj.getString("skuSpecCode");
            String unitName = obj.getString("unitName");
            Long unitId = Long.parseLong(obj.getString("unitId"));
            BigDecimal supplyPrice = new BigDecimal(obj.getString("supplyPrice"));
            BigDecimal marketPrice = new BigDecimal(obj.getString("marketPrice"));
            Long quantityOut = Long.parseLong(obj.getString("quantityOut"));
            String barcode = obj.getString("barcode");
            String enterpriceCode = obj.getString("enterpriceCode");
            jobProduct.setSkuCode(skuCode);
            jobProduct.setSkuPic(skuPic);
            jobProduct.setProductName(productName);
            jobProduct.setSkuSpecCode(skuSpecCode);
            jobProduct.setUnitName(unitName);
            jobProduct.setUnitId(unitId);
            jobProduct.setTotal(supplyPrice);
            jobProduct.setMarketPrice(marketPrice);
            jobProduct.setBarcode(barcode);
            jobProduct.setEnterpriceCode(enterpriceCode);
            jobProduct.setQuantity(quantityOut);
            inventoryJobProductDao.insert(jobProduct);
            //减少出库计划详情的出库数量
            InventoryOutPlanDetail outPlanDetail = inventoryOutPlanDetailService.getById(id);
            outPlanDetail.setQuantity(outPlanDetail.getQuantity() - quantityOut);
            inventoryOutPlanDetailDao.updateById(outPlanDetail);
            //出库作业单的包装码明细
            JSONArray packLabelJsonArray = JSONArray.parseArray(inventoryJobForm.getProductPackLabeJson());
            for (int j = 0; j < packLabelJsonArray.size(); j++) {
                InventoryJobLabel jobLabel = new InventoryJobLabel();
                JSONObject packLabelObj = (JSONObject) packLabelJsonArray.get(j);
                String packSkuCode = packLabelObj.getString("skuCode");
                //判断出库产品数据的skuCode等于包装码数据的skuCode
                if (skuCode.equals(packSkuCode)) {
                    jobLabel.setJobId(inventoryInoutJob.getId());
                    jobLabel.setJobProductId(jobProduct.getId());
                    Long packLabeId = Long.parseLong(packLabelObj.getString("id"));
                    String packLabeCode = packLabelObj.getString("code");
                    Integer packQuantityOut = Integer.valueOf(packLabelObj.getString("quantityOut"));
                    Long packId = Long.parseLong(packLabelObj.getString("packId"));
                    String packName = packLabelObj.getString("packName");
                    Long packLabeQuantity = Long.parseLong(packLabelObj.getString("quantity"));
                    jobLabel.setPackName(packName);
                    jobLabel.setPackId(packId);
                    jobLabel.setQuantity(new Long(packQuantityOut));
                    jobLabel.setPackLabeCode(packLabeCode);
                    jobLabel.setPackLabeId(packLabeId);
                    jobLabel.setPackLabeQuantity(packLabeQuantity);
                    inventoryJobLabelDao.insert(jobLabel);
                    //产品包装条码数量变化记录
                    //查询包装码
                    JsonResult<ProductPackLabelVO> packLabelJson = enterpriseClient.getProductPackLabelById(packLabeId);
                    //出库调用的接口
                    JsonResult<ProductPackLabelForm> jsonResult = enterpriseClient.extractPackLabel4InventoryOut(packLabeCode,packQuantityOut.intValue(),1);
                    if (jsonResult.getCode() != Result.Code.SUCCESS.getCode()) {
                        throw new BusinessException(jsonResult.getMsg());
                    }
                  /*  productPackLabelDetailForm.setPackLabelCode(packLabelJson.getData().getCode());
                    productPackLabelDetailForm.setSurplusQuantity(packQuantityOut);
                    productPackLabelDetailForm.setJobId(inventoryInoutJob.getId());
                    enterpriseClient.addProductPackLabelDetail(productPackLabelDetailForm);*/
                    //enterpriseClient.updateProductPackLabe(packLabeId,packLabelJson.getData().getSurplusQuantity() - packQuantityOut);
                    //产品包装条码数量变化记录
                    ProductPackLabelOut productPackLabelOut = new ProductPackLabelOut();
                    productPackLabelOut.setQuantityCurrent(packLabelJson.getData().getQuantity());
                    productPackLabelOut.setPackLabelId(packLabelJson.getData().getId());
                    productPackLabelOut.setQuantityAfter((int) (packLabelJson.getData().getSurplusQuantity() - packQuantityOut.longValue()));
                    productPackLabelOut.setQuantityOut((int) packQuantityOut.longValue());
                    enterpriseClient.addProductPackLabelOut(productPackLabelOut);
                    //扣减库存和库存变动
                    //查询是否有库存数据
//            CabInventoryProduct cabInventory = cabInventoryProductDao.getCabInventoryProductVOBySkuCode(skuCode);
                    JsonResult<CabInventoryProduct> jsonInventory = enterpriseClient.getCabInventoryProductVOBySkuCode(skuCode);
                    CabInventoryProduct cabInventory = jsonInventory.getData();

                    CabInventoryProductRecord inventoryProductRecord = new CabInventoryProductRecord();
                    if (cabInventory.getId() == null) {
                        throw new BusinessException("SKU[" + skuCode + "]产品还未入库");
                    } else {
                        if (packQuantityOut > cabInventory.getQuantity()) {
                            //出库数大于库存数
                            throw new BusinessException("SKU[" + skuCode + "]产品出库数大于库存数");
                        } else {
                            //库存变动记录的值
                            inventoryProductRecord.setInventoryProductId(cabInventory.getId());
                            inventoryProductRecord.setQuantityCurrent(cabInventory.getQuantity());//当前库存
                            inventoryProductRecord.setQuantityAfter((int) (cabInventory.getQuantity() - packQuantityOut));//变动后库存
                            //库存变动
                            cabInventory.setQuantity((int) (cabInventory.getQuantity() - packQuantityOut));
                            enterpriseClient.updateCabInventoryProduct(cabInventory);
                            //库存变动记录
                            inventoryProductRecord.setPlanId(outPlanVO.getId());
                            inventoryProductRecord.setJobId(inventoryInoutJob.getId());
                            inventoryProductRecord.setSkuCode(skuCode);
                            inventoryProductRecord.setType(CabInventoryProductRecord.Type.out);
                            enterpriseClient.addCabInventoryProductRecord(inventoryProductRecord);
                        }
                    }
                }
            }

        }
        //根据出库单id查询这个订单新的包装码数据
        /*JsonResult<List<ProductPackLabelDetailVO>> packLabelDetaiJson = enterpriseClient.getPackLabelDetaiListByJobId(inventoryInoutJob.getId());
        List<ProductPackLabelDetailVO> list = packLabelDetaiJson.getData();
        String jsonStr = JSONObject.toJSONString(list);
        inventoryJobForm.setProductPackLabeJson(jsonStr);*/
        //出库类型是调拨到云仓才同步数据
        QueryWrapper<WarehouseInventoryType> typeWrapper = new QueryWrapper<>();
        typeWrapper.eq("code",outPlanVO.getInoutTypeCode());
        WarehouseInventoryType inventoryType = warehouseInventoryTypeService.getOne(typeWrapper);
        if (inventoryType.getCode().equals("allotCloudWarehouse")) {
            //将数据存好 同步平台数据
            inventoryJobForm.setPlanId(outPlanVO.getId());
            inventoryJobForm.setPlanCode(outPlanVO.getCode());
            inventoryJobForm.setCode(enterrpriseCode +"_"+ inventoryInoutJob.getCode());
            inventoryJobForm.setLoginUsername(loginUsername);
            inventoryJobForm.setEnterpriseId(Long.parseLong(enterpriseId));
            //查询出库仓数据 出库仓
            WarehouseVO warehouseVO = warehouseDao.get4appById(outPlanVO.getOutWarehouseId());
            inventoryJobForm.setOutWarehouseName(warehouseVO.getName());
            //查询出库的物流公司
            JsonResult<TransportCompany> companyJson = enterpriseClient.getTransportCompanyById(inventoryJobForm.getCompanyId());
            inventoryJobForm.setLogisticsCompany(companyJson.getData().getName());
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            inventoryJobForm.setSendTime(df.format(outPlanVO.getSendTime()));
            //查询当前登录信息
            JsonResult<UserVO> userInfo = userClient.getUserInfo(JwtUtils.getLoginUserId());
            if(userInfo.getCode() == Result.Code.SUCCESS.getCode()){
                inventoryJobForm.setConsignerMobel(userInfo.getData().getPhone());
            }
            //同步到平台端
            String jsonObject = JSONUtil.toJsonStr(inventoryJobForm);
            /*JsonResult addOutResult = platformClient.addOutInventoryInoutJob(jsonObject);
            if (addOutResult.getCode() != Result.Code.SUCCESS.getCode()) {
                throw new BusinessException("同步到平台异常" + addOutResult.getMsg());
            }*/
            /*final String reqUri = gatewayUrl + "platform/order/admin/inventoryInoutJob/addOutInventoryInoutJob";
            try {
                String tokenJson = HttpHelper.httpPost(reqUri, jsonObject);
                System.out.println(String.format("==========================>this is response:{%s}", tokenJson));
            } catch (Exception e) {
                e.printStackTrace();
            }*/
        }
    }


    @Transactional
    @Override
    public JsonResult saveInventoryInoutJob(List<OrderDeliveryVO> list, Integer warhouseId) {
        //出/入库作业单记录 添加
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String today = format.format(new Date());
        for (int i = 0; i < list.size(); i++) {
            //出/入库作业产品
            InventoryInoutJob inventoryInoutJob = new InventoryInoutJob();
            Integer maxCode = dynamicDao.getDayMaxNo("ord_inventory_inout_job");
            String code = CodeUtil.getCode(maxCode);
            inventoryInoutJob.setCode(code)
                    .setInventoryInoutId(Long.valueOf(warhouseId))
                    .setInoutType(InventoryInoutJob.InoutType.valueOf("in"))
                    .setNo(Integer.valueOf(code))
                    .setDay(Integer.valueOf(today))
                    .setRemark(list.get(i).getRemark());
            inventoryInoutJob.setStatus(InventoryInoutJob.Status.sign);
            inventoryInoutJob.setId(null);
            inventoryInoutJobDao.insert(inventoryInoutJob);
            //出/入库作业产品明细
            InventoryJobProduct jobProduct = new InventoryJobProduct();
            jobProduct.setJobId(inventoryInoutJob.getId());
            jobProduct.setSkuCode(list.get(i).getSkuCode());
            jobProduct.setQuantity(null);
            jobProduct.setCreateTime(LocalDateTime.now());
            inventoryJobProductDao.insert(jobProduct);
            //出/入库作业产品明细 包装
            InventoryJobLabel jobLabel = new InventoryJobLabel();
            jobLabel.setJobId(inventoryInoutJob.getId());
            jobLabel.setJobProductId(jobProduct.getId());
            jobLabel.setPackLabeCode(list.get(i).getPackLabelCode());
            inventoryJobLabelDao.insert(jobLabel);
            //产品库存
            System.out.println("code" + list.get(i).getSkuCode());
            JsonResult<CabInventoryProduct> jsonInventory = enterpriseClient.getCabInventoryProductVOBySkuCode(list.get(i).getSkuCode());
            CabInventoryProduct cabInventory = jsonInventory.getData();
            ;

            CabInventoryProductForm cabInventoryProduct = new CabInventoryProductForm();
            CabInventoryProductRecord inventoryProductRecord = new CabInventoryProductRecord();
            if (cabInventory == null) {
                cabInventoryProduct.setId(null)
                        .setSkuCode(list.get(i).getSkuCode())
                        .setWarehouseId(Long.valueOf(warhouseId))
                        .setQuantity(list.get(i).getRealReceive());
                cabInventoryProduct.setJobId(inventoryInoutJob.getId());
                enterpriseClient.addCabInventoryProduct(cabInventoryProduct);
                //库存变动记录的值
                inventoryProductRecord.setInventoryProductId(cabInventoryProduct.getId())
                        .setQuantityCurrent(cabInventoryProduct.getQuantity())
                        .setQuantityAfter(cabInventoryProduct.getQuantity())
                        .setInventoryProductId(cabInventoryProduct.getId());
            } else {
                //库存变动记录的值
                inventoryProductRecord.setInventoryProductId(cabInventory.getId());
                //当前库存
                inventoryProductRecord.setQuantityCurrent(cabInventory.getQuantity());
                //变动后库存
                inventoryProductRecord.setQuantityAfter(cabInventory.getQuantity() + list.get(i).getRealReceive());
                inventoryProductRecord.setInventoryProductId(cabInventory.getId());
                //库存变动
                cabInventory.setQuantity(cabInventory.getQuantity() + list.get(i).getRealReceive());
                enterpriseClient.updateCabInventoryProduct(cabInventory);

            }
            //库存变动记录
            inventoryProductRecord.setJobId(inventoryInoutJob.getId());
            inventoryProductRecord.setSkuCode(list.get(i).getSkuCode());
            inventoryProductRecord.setType(CabInventoryProductRecord.Type.valueOf("in"));
            inventoryProductRecord.setPlanId(null);
            enterpriseClient.addCabInventoryProductRecord(inventoryProductRecord);

            //将配送明细状态改为已入库
            OrderDeliveryDetail orderDeliveryDetail = new OrderDeliveryDetail();
            orderDeliveryDetail.setId(list.get(i).getId());
            orderDeliveryDetail.setStatus(OrderDeliveryDetail.Status.InStock);
            orderDeliveryDetailService.updateById(orderDeliveryDetail);
        }


        return JsonResult.success("修改成功");
    }

    @Transactional
    @Override
    public JsonResult outOfStock(ScanDeliveryVo scanPickupInfo, Integer realReceive, String remark) {

        //判断是否被扫描
        if (scanPickupInfo.getIsScan()) {
            throw new BusinessException(scanPickupInfo.getPackLabelCode() + "已被扫描过");
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String today = format.format(new Date());
        //出库作业单
        InventoryInoutJob inventoryInoutJob = new InventoryInoutJob();
        Integer maxCode = dynamicDao.getDayMaxNo("ord_inventory_inout_job");
        String code = CodeUtil.getCode(maxCode);
        inventoryInoutJob.setId(null);
        inventoryInoutJob.setCode(code);
        inventoryInoutJob.setInoutType(InventoryInoutJob.InoutType.out);
        inventoryInoutJob.setQuantity(Long.valueOf(realReceive));
        inventoryInoutJob.setRemark(scanPickupInfo.getRemark());
        inventoryInoutJob.setNo(Integer.valueOf(code));
        inventoryInoutJob.setDay(Integer.valueOf(today));
        inventoryInoutJob.setSkuCode(scanPickupInfo.getSkuCode());
        inventoryInoutJob.setStatus(InventoryInoutJob.Status.sign);
        //来自小程序
        inventoryInoutJob.setFromSign(InventoryInoutJob.FromSign.app);
        inventoryInoutJobDao.insert(inventoryInoutJob);
        //出库作业单的产品明细
        InventoryJobProduct jobProduct = new InventoryJobProduct();
        jobProduct.setSkuCode(scanPickupInfo.getSkuCode());
        jobProduct.setSkuPic(scanPickupInfo.getProductImg());
        jobProduct.setProductName(scanPickupInfo.getProductName());
        jobProduct.setSkuSpecCode(scanPickupInfo.getPackSpecCode());
        jobProduct.setTotal(BigDecimal.valueOf(scanPickupInfo.getSupplyPrice()));
        jobProduct.setMarketPrice(BigDecimal.valueOf(scanPickupInfo.getMarketPrice()));
        jobProduct.setJobId(inventoryInoutJob.getId());

//        jobProduct.setBarcode(barcode);
//        jobProduct.setEnterpriceCode(enterpriceCode);
        jobProduct.setQuantity(Long.valueOf(realReceive));
        inventoryJobProductDao.insert(jobProduct);
        //扣减库存和库存变动
        //查询是否有库存数据
        JsonResult<CabInventoryProduct> jsonInventory = enterpriseClient.getCabInventoryProductVOBySkuCode(scanPickupInfo.getSkuCode());
        CabInventoryProduct cabInventory = jsonInventory.getData();
        ;
        CabInventoryProductRecord inventoryProductRecord = new CabInventoryProductRecord();
        if (cabInventory == null) {
            throw new BusinessException("SKU[" + scanPickupInfo.getSkuCode() + "]产品还未入库");
        } else {
            if (realReceive > cabInventory.getQuantity()) {
                //出库数大于库存数
                throw new BusinessException("SKU[" + scanPickupInfo.getSkuCode() + "]产品出库数大于库存数");
            } else {
                //库存变动记录的值
                inventoryProductRecord.setInventoryProductId(cabInventory.getId());
                inventoryProductRecord.setQuantityCurrent(cabInventory.getQuantity());//当前库存
                inventoryProductRecord.setQuantityAfter((int) (cabInventory.getQuantity() - realReceive));//变动后库存
                //库存变动
                cabInventory.setQuantity((int) (cabInventory.getQuantity() - realReceive));
                enterpriseClient.updateCabInventoryProduct(cabInventory);
                //库存变动记录
//                inventoryProductRecord.setPlanId(outPlanVO.getId());
                inventoryProductRecord.setJobId(inventoryInoutJob.getId());
                inventoryProductRecord.setSkuCode(scanPickupInfo.getSkuCode());
                inventoryProductRecord.setType(CabInventoryProductRecord.Type.out);
                enterpriseClient.addCabInventoryProductRecord(inventoryProductRecord);
            }
            //出库作业单的包装码明细
            InventoryJobLabel jobLabel = new InventoryJobLabel();
            jobLabel.setPackName(scanPickupInfo.getPackSpecCode());
//            jobLabel.setPackId(packId);
            jobLabel.setQuantity(new Long(realReceive));
            jobLabel.setPackLabeCode(scanPickupInfo.getPackLabelCode());
            jobLabel.setJobId(inventoryInoutJob.getId());
            jobLabel.setJobProductId(jobProduct.getId());
//            jobLabel.setPackLabeId(Long.valueOf(scanPickupInfo.getPackLabelId()));
//            jobLabel.setPackLabeQuantity(Long.valueOf(scanPickupInfo.getPackLabelQuantity()));
            inventoryJobLabelDao.insert(jobLabel);
            //查询包装码
//            JsonResult<ProductPackLabelVO> packLabelJson = enterpriseClient.getProductPackLabelById(Long.valueOf(scanPickupInfo.getPackLabelId()));
            ProductPackLabelDetailForm productPackLabelDetailForm = new ProductPackLabelDetailForm();
            //调用接口 往包装码详情表存入数据并扣减剩余数量
//            productPackLabelDetailForm.setPackLabelCode(packLabelJson.getData().getCode());
            productPackLabelDetailForm.setSurplusQuantity(realReceive);
            productPackLabelDetailForm.setJobId(inventoryInoutJob.getId());
            enterpriseClient.addProductPackLabelDetail(productPackLabelDetailForm);
        }
        //修改扫描状态
        OrderDistributionLabel orderDistributionLabel = new OrderDistributionLabel();
        orderDistributionLabel.setIsScan(true);
        orderDistributionLabel.setStatus(OrderDistributionLabel.Status.receive);
        QueryWrapper<OrderDistributionLabel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pack_label_code", scanPickupInfo.getPackLabelCode());
        orderDistributionLabelService.update(orderDistributionLabel, queryWrapper);
        //配送明细
        OrderDeliveryDetail orderDeliveryDetail = new OrderDeliveryDetail();
        orderDeliveryDetail.setId(scanPickupInfo.getId());
        orderDeliveryDetail.setRemark(remark);
        orderDeliveryDetail.setStatus(OrderDeliveryDetail.Status.done);
        orderDeliveryDetailService.updateById(orderDeliveryDetail);
        return JsonResult.success();
    }

    @Override
    @Transactional
    public void inventoryIn(List<OrderDeliveryLabelVO> labels) {
        String enterpriseCode=JwtUtils.getEnterpriseCode();
        if (CollectionUtils.isEmpty(labels)){
            throw new BusinessException("参数异常");
        }
        String loginUsername = JwtUtils.getLoginUsername();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String today = format.format(new Date());
        //查询企业id
        String enterpriseId = String.valueOf(JwtUtils.getEnterpriseId());
        //出库作业单
        InventoryInoutJob inventoryInoutJob = new InventoryInoutJob();
        Integer maxCode = dynamicDao.getDayMaxNo("ord_inventory_inout_job");
        String code = CodeUtil.getCode(maxCode);
        inventoryInoutJob.setCode("SI-IN-"+today+ code);
        inventoryInoutJob.setInoutType(InventoryInoutJob.InoutType.in);
        inventoryInoutJob.setQuantity(getSumQuantity(labels));
        inventoryInoutJob.setNo(Integer.valueOf(code));
        inventoryInoutJob.setDay(Integer.valueOf(today));
        inventoryInoutJob.setStatus(InventoryInoutJob.Status.sign);
        //来自小程序
        inventoryInoutJob.setFromSign(InventoryInoutJob.FromSign.app);
        inventoryInoutJob.setDeliveryId(labels.get(0).getDeliveryId());
        inventoryInoutJobDao.insert(inventoryInoutJob);
        Map<String,Long> skuMap=new HashMap<>();
        for (OrderDeliveryLabelVO orderDeliveryLabelVO:labels){

            if (!skuMap.containsKey(orderDeliveryLabelVO.getSkuCode())){
                InventoryJobProduct jobProduct = new InventoryJobProduct();
                jobProduct.setJobId(inventoryInoutJob.getId());
                jobProduct.setSkuCode(orderDeliveryLabelVO.getSkuCode());
                jobProduct.setSkuPic(orderDeliveryLabelVO.getSkuPic());
                jobProduct.setProductName(orderDeliveryLabelVO.getSkuName());
                jobProduct.setSkuSpecCode(orderDeliveryLabelVO.getSkuSpec());
                jobProduct.setUnitName(orderDeliveryLabelVO.getUnitName());
                jobProduct.setUnitId(orderDeliveryLabelVO.getUnitId());
                jobProduct.setTotal(orderDeliveryLabelVO.getSupplyPrice());
                jobProduct.setMarketPrice(orderDeliveryLabelVO.getMarketPrice());
                jobProduct.setBarcode(orderDeliveryLabelVO.getBarcode());
                jobProduct.setEnterpriceCode(enterpriseCode);
                jobProduct.setQuantity(Long.valueOf(orderDeliveryLabelVO.getQuantityInOut()));
                inventoryJobProductDao.insert(jobProduct);
                skuMap.put(orderDeliveryLabelVO.getSkuCode(),jobProduct.getId());
            }
            InventoryJobLabel jobLabel = new InventoryJobLabel();
            jobLabel.setJobId(inventoryInoutJob.getId());
            jobLabel.setJobProductId(skuMap.get(orderDeliveryLabelVO.getSkuCode()));
            jobLabel.setQuantity(Long.valueOf(orderDeliveryLabelVO.getQuantityInOut()));
            jobLabel.setPackLabeCode(orderDeliveryLabelVO.getPackLabelCode());
            jobLabel.setPackLabeId(orderDeliveryLabelVO.getPackLabelId());
            jobLabel.setDeliveryId(orderDeliveryLabelVO.getDeliveryId());
            jobLabel.setDeliveryDetailId(orderDeliveryLabelVO.getDeliveryDetailId());
            jobLabel.setWarehouseId(orderDeliveryLabelVO.getWarehouseId());
            jobLabel.setAreaId(orderDeliveryLabelVO.getAreaId());
            jobLabel.setShelfId(orderDeliveryLabelVO.getShelfId());
            jobLabel.setSpaceId(orderDeliveryLabelVO.getSpaceId());
            jobLabel.setBoxId(orderDeliveryLabelVO.getBoxId());
            jobLabel.setStatus(InventoryJobLabel.Status.storage);
            inventoryJobLabelDao.insert(jobLabel);

            BoxLabel boxLabel=new BoxLabel();
            boxLabel.setBoxId(orderDeliveryLabelVO.getBoxId());
            boxLabel.setSkuCode(orderDeliveryLabelVO.getSkuCode());
            boxLabel.setPackLabeCode(orderDeliveryLabelVO.getPackLabelCode());
            boxLabel.setPackLabeQuantity(Long.valueOf(orderDeliveryLabelVO.getQuantityInOut()));
            boxLabel.setPackLabeId(orderDeliveryLabelVO.getPackLabelId());
            boxLabel.setPackName(orderDeliveryLabelVO.getPackName());
            boxLabel.setQuantity(Long.valueOf(orderDeliveryLabelVO.getQuantityInOut()));
            boxLabel.setWarehouseId(orderDeliveryLabelVO.getWarehouseId());
            boxLabel.setAreaId(orderDeliveryLabelVO.getAreaId());
            boxLabel.setShelfId(orderDeliveryLabelVO.getShelfId());
            boxLabel.setSpaceId(orderDeliveryLabelVO.getSpaceId());
            boxLabel.setBoxId(orderDeliveryLabelVO.getBoxId());
            boxLabelService.save(boxLabel);


            String skuCode=orderDeliveryLabelVO.getSkuCode();
            //增加库存和库存变动
            //查询是否有库存数据
            JsonResult<CabInventoryProduct> jsonInventory = enterpriseClient.getCabInventoryProductVOBySkuCode2(skuCode,orderDeliveryLabelVO.getWarehouseId(),0);
            CabInventoryProduct cabInventory = jsonInventory.getData();
//            cabInventory.setWarehouseId(orderDeliveryLabelVO.getWarehouseId());

            CabInventoryProductForm cabInventoryProduct = new CabInventoryProductForm();
            cabInventoryProduct.setWarehouseId(orderDeliveryLabelVO.getWarehouseId());
            CabInventoryProductRecord inventoryProductRecord = new CabInventoryProductRecord();
            Integer quantity=orderDeliveryLabelVO.getQuantityInOut();
            if (cabInventory.getId() == null) {
                //区分是签收刀具入库还是生产入库
                cabInventoryProduct.setType(CabInventoryProduct.Type.knife);
//                cabInventoryProduct.setPlanId(inoutVO.getId());
//                cabInventoryProduct.setJobId(inventoryInoutJob.getId());
                cabInventoryProduct.setSkuCode(skuCode);
                cabInventoryProduct.setQuantity((int) quantity.longValue());
                enterpriseClient.addCabInventoryProduct(cabInventoryProduct);
                //库存变动记录的值
                JsonResult<CabInventoryProduct> json = enterpriseClient.getCabInventoryProductVOBySkuCode(skuCode);
                inventoryProductRecord.setInventoryProductId(json.getData().getId());
                inventoryProductRecord.setQuantityCurrent((int) quantity.longValue());
                inventoryProductRecord.setQuantityAfter((int) quantity.longValue());
            } else {
                //库存变动记录的值
                inventoryProductRecord.setInventoryProductId(cabInventory.getId());
                inventoryProductRecord.setQuantityCurrent(cabInventory.getQuantity());//当前库存
                inventoryProductRecord.setQuantityAfter(cabInventory.getQuantity() + (int) quantity.longValue());//变动后库存
                //库存变动
                cabInventory.setQuantity(cabInventory.getQuantity() + (int) quantity.longValue());
                enterpriseClient.updateCabInventoryProduct(cabInventory);
            }
//            //库存变动记录
//            inventoryProductRecord.setPlanId(inoutVO.getId());
            inventoryProductRecord.setJobId(inventoryInoutJob.getId());
            inventoryProductRecord.setSkuCode(skuCode);
            inventoryProductRecord.setType(CabInventoryProductRecord.Type.valueOf("in"));
            enterpriseClient.addCabInventoryProductRecord(inventoryProductRecord);

        }


    }

    @Transactional
    @Override
    public void addStorageWork(InventoryInoutJobVO inventoryInoutJobVO) {
        if(inventoryInoutJobVO == null){
           throw  new BusinessException("添加入库作业参数异常");
        }
        PalletBoxListVO palletBox = palletBoxListDao.getPalletBox(inventoryInoutJobVO.getBoxCode(),null);
        if(palletBox == null){
            throw  new BusinessException("料箱不存在");
        }
        List<InventoryJobLabelVO> jobLabelList = inventoryInoutJobVO.getJobLabelList();
        if(CollectionUtils.isEmpty(jobLabelList)){
            throw  new BusinessException("包装条码参数异常");
        }
        //入库作业单添加
        Map<String,String> skuCodeMap=new HashMap<>();
        String today = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
        InventoryInoutJob inventoryInoutJob = new InventoryInoutJob();

        //入库仓id
        Long warehouseId = palletBox.getWarehouseId();
        Integer maxCode = dynamicDao.getDayMaxNo("ord_inventory_inout_job");
        String code = CodeUtil.getCode(maxCode);
        inventoryInoutJob.setSkuCode(inventoryInoutJobVO.getSkuCode());
        //生产入库
        //生产入库计划的入库类型
        String inoutTypeCode = null;
        if("production".equals(inventoryInoutJobVO.getInoutTypeCode())){
            InventoryInoutVO inoutVO = inventoryInoutService.get4appById(inventoryInoutJobVO.getPlanId());
            inoutTypeCode = inoutVO.getInoutTypeCode();
            inventoryInoutJob.setCode(inoutVO.getCode() + today + code);
            inventoryInoutJob.setPlanCode(inoutVO.getCode());
            inventoryInoutJob.setPlanId(inoutVO.getId());
           //采购入库
        }else if("purchase".equals(inventoryInoutJobVO.getInoutTypeCode())){
            PurchaseVO purchaseVO = purchaseService.get4appById(inventoryInoutJobVO.getPlanId());
            inventoryInoutJob.setCode(purchaseVO.getCode() + today + code);
            inventoryInoutJob.setPlanCode(purchaseVO.getCode());
            inventoryInoutJob.setPlanId(purchaseVO.getId());
        }

        inventoryInoutJob.setSignStationName(inventoryInoutJobVO.getSignStationName());
        inventoryInoutJob.setRemark(inventoryInoutJobVO.getRemark());
        inventoryInoutJob.setInoutType(InventoryInoutJob.InoutType.valueOf("in"));
        inventoryInoutJob.setStatus(InventoryInoutJob.Status.storage);
        inventoryInoutJob.setNo(Integer.valueOf(code));
        inventoryInoutJob.setDay(Integer.valueOf(today));
        inventoryInoutJob.setCreatorName(JwtUtils.getLoginUsername());
        inventoryInoutJob.setWarehouseId(palletBox.getWarehouseId());
        inventoryInoutJob.setWarehouseName(palletBox.getWarehouseName());
        inventoryInoutJob.setInoutTypeCode(inventoryInoutJobVO.getInoutTypeCode());
        inventoryInoutJob.setInoutTypeName(inventoryInoutJobVO.getInoutTypeName());
        inventoryInoutJobDao.insert(inventoryInoutJob);
        Long jobProductId = null;
        for (InventoryJobLabelVO item : jobLabelList){
            //查询入库签收的产品
            InventoryJobSignProductDetailVO signProductDetailVO = inventoryJobSignProductDetailDao.get4appById(item.getSignProductDetailId());
           /* QueryWrapper<InventoryInoutDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("sku_code", item.getSkuCode());
            queryWrapper.eq("plan_id",inventoryInoutJobVO.getPlanId());
            InventoryInoutDetail inoutDetail = inventoryInoutDetailDao.selectOne(queryWrapper);*/
            //入库作业单产品记录
            if(!skuCodeMap.containsKey(item.getSkuCode())){
                InventoryJobProduct jobProduct = new InventoryJobProduct();
                jobProduct.setJobId(inventoryInoutJob.getId())
                        .setSkuCode(signProductDetailVO.getSkuCode())
                        .setProductName(signProductDetailVO.getProductName())
                        .setUnitName(signProductDetailVO.getUnitName())
                        .setProductType(signProductDetailVO.getProductType())
                        .setProductCode(signProductDetailVO.getProductCode())
                        .setInoutType(InventoryJobProduct.InoutType.in);
                        inventoryJobProductDao.insert(jobProduct);
                jobProductId = jobProduct.getId();
                skuCodeMap.put(signProductDetailVO.getSkuCode(),signProductDetailVO.getSkuCode());
            }
            //条码入库
            InventoryJobLabel inventoryJobLabel = inventoryJobLabelDao.selectById(item.getId());
            inventoryJobLabel.setJobId(inventoryInoutJob.getId());
            inventoryJobLabel.setJobProductId(jobProductId);
            inventoryJobLabel.setStorageQuantity(item.getStorageQuantity());
            inventoryJobLabel.setStatus(InventoryJobLabel.Status.storage);
            inventoryJobLabel.setInoutType(InventoryJobLabel.InoutType.in);
            inventoryJobLabel.setBoxId(palletBox.getBoxId());
            inventoryJobLabel.setWarehouseId(palletBox.getWarehouseId());
            inventoryJobLabel.setAreaId(palletBox.getAreaId());
            inventoryJobLabel.setShelfId(palletBox.getShelfId());
            inventoryJobLabel.setSpaceId(palletBox.getSpaceId());
            inventoryJobLabel.setInoutTypeCode(inventoryInoutJobVO.getInoutTypeCode());
            inventoryJobLabel.setInoutTypeName(inventoryInoutJobVO.getInoutTypeName());
            inventoryJobLabelDao.updateById(inventoryJobLabel);
            //料箱存储包装编码表
            BoxLabel boxLabel=new BoxLabel();
            boxLabel.setBoxId(palletBox.getBoxId());
            boxLabel.setSkuCode(item.getSkuCode());
            boxLabel.setPackLabeCode(inventoryJobLabel.getPackLabeCode());
            boxLabel.setPackLabeQuantity(Long.valueOf(item.getStorageQuantity()));
            boxLabel.setPackLabeId(inventoryJobLabel.getPackLabeId());
            boxLabel.setPackName(inventoryJobLabel.getPackName());
            boxLabel.setQuantity(Long.valueOf(item.getStorageQuantity()));
            boxLabel.setWarehouseId(palletBox.getWarehouseId());
            boxLabel.setAreaId(palletBox.getAreaId());
            boxLabel.setShelfId(palletBox.getShelfId());
            boxLabel.setSpaceId(palletBox.getSpaceId());
            boxLabelService.save(boxLabel);
            //修改计划状态
            storageWorkPlanStatus(inventoryInoutJobVO.getPlanId(),inventoryInoutJobVO.getInoutTypeCode());
            //查询入库产品信息
            //InventoryJobProduct inventoryJobProduct = inventoryJobProductDao.selectById(inventoryJobLabel.getJobProductId());
            //将包装条码加上料箱
            ProductPackLabel packLabel = productPackLabelService.getById(inventoryJobLabel.getPackLabeId());
            packLabel.setId(inventoryJobLabel.getPackLabeId());
            packLabel.setBoxId(palletBox.getBoxId());
            packLabel.setWarehouseId(palletBox.getWarehouseId());
            packLabel.setAreaId(palletBox.getAreaId());
            packLabel.setShelfId(palletBox.getShelfId());
            packLabel.setSpaceId(palletBox.getSpaceId());
            productPackLabelService.updateById(packLabel);
            //调用接口 extractLabel4InventoryIn
            com.wing.product.model.request.ProductPackLabelForm productPackLabelForm = productPackLabelService.extractLabel4InventoryIn(inventoryJobLabel.getPackLabeCode(), item.getStorageQuantity().intValue(), 1);

            //增加库存和库存变动
            //查询此产品从自采、平台导入、本地导入的数据
            List<com.wing.order.model.entity.CabInventoryProduct> inventoryList = cabInventoryProductService.getInventoryProductBySkuType(signProductDetailVO.getSkuCode());
            if(CollectionUtils.isNotEmpty(inventoryList)){
                for (com.wing.order.model.entity.CabInventoryProduct inventoryProduct : inventoryList){
                    if(inventoryProduct.getWarehouseId()!=null && inventoryProduct.getWarehouseId() == 0){
                        cabInventoryProductService.removeById(inventoryProduct);
                    }
                }

            }

            //查询库存
            com.wing.order.model.entity.CabInventoryProduct cabInventory = cabInventoryProductService.getInventoryProductVOBySkuCode(signProductDetailVO.getSkuCode(), warehouseId, 0);
            com.wing.order.model.entity.CabInventoryProduct cabInventoryProduct = new com.wing.order.model.entity.CabInventoryProduct();
            com.wing.order.model.entity.CabInventoryProductRecord inventoryProductRecord = new com.wing.order.model.entity.CabInventoryProductRecord();
            if (cabInventory == null) {
                //区分是签收刀具入库还是生产入库
                    if("cutter".equals(inoutTypeCode)){
                    cabInventoryProduct.setType(com.wing.order.model.entity.CabInventoryProduct.Type.knife);
                    com.wing.product.model.response.ProductDetailVO productDetailVO = productDetailService.getProductInfoBySkuCode(signProductDetailVO.getSkuCode());
                    String sourceType = productDetailVO.getDataSourceType().name();
                    //数据来源:oneself(0,自采);platform(1,平台);local(2,本地)
                    if(sourceType.equals("oneself")){
                        cabInventoryProduct.setSkuType(1);
                    }else if(sourceType.equals("platform")){
                        cabInventoryProduct.setSkuType(2);
                    }else if(sourceType.equals("local")){
                        cabInventoryProduct.setSkuType(0);
                    }
                }else{
                    cabInventoryProduct.setType(com.wing.order.model.entity.CabInventoryProduct.Type.make);
                    cabInventoryProduct.setSkuType(0);//云端制造
                }
                cabInventoryProduct.setWarehouseId(warehouseId);
                cabInventoryProduct.setJobId(inventoryInoutJob.getId());
                cabInventoryProduct.setSkuCode(signProductDetailVO.getSkuCode());
                cabInventoryProduct.setQuantity(item.getStorageQuantity().intValue());
                cabInventoryProductService.save(cabInventoryProduct);

                //库存变动记录的值
                //JsonResult<CabInventoryProduct> json = enterpriseClient.getCabInventoryProductVOBySkuCode2(signProductDetailVO.getSkuCode(),warehouseId,0);
                inventoryProductRecord.setInventoryProductId(cabInventoryProduct.getId());
                inventoryProductRecord.setQuantityCurrent(item.getStorageQuantity().intValue());
                inventoryProductRecord.setQuantityAfter(item.getStorageQuantity().intValue());
            } else {
                //库存变动记录的值
                inventoryProductRecord.setInventoryProductId(cabInventory.getId());
                inventoryProductRecord.setQuantityCurrent(cabInventory.getQuantity());//当前库存
                inventoryProductRecord.setQuantityAfter(cabInventory.getQuantity() + item.getStorageQuantity().intValue());//变动后库存
                //库存变动
                cabInventory.setQuantity(cabInventory.getQuantity() + item.getStorageQuantity().intValue());
                cabInventoryProductService.updateById(cabInventory);
            }
            //库存变动记录
            inventoryProductRecord.setJobId(inventoryInoutJob.getId());
            inventoryProductRecord.setSkuCode(signProductDetailVO.getSkuCode());
            inventoryProductRecord.setType(com.wing.order.model.entity.CabInventoryProductRecord.Type.valueOf("in"));
            String warehouseInventoryTypeCode = "";
            if("production".equals(inventoryInoutJobVO.getInoutTypeCode())){
                // 生产入库
                warehouseInventoryTypeCode = "QT_RK";
            }else if("purchase".equals(inventoryInoutJobVO.getInoutTypeCode())){
                //采购入库
                warehouseInventoryTypeCode = "CG_RK";
            }
            if(StringUtils.isNotBlank(warehouseInventoryTypeCode)){
                WarehouseInventoryType warehouseInventoryType = warehouseInventoryTypeService.getOne(new QueryWrapper<WarehouseInventoryType>().eq("code", warehouseInventoryTypeCode));
                inventoryProductRecord.setWarehouseInventoryTypeId(warehouseInventoryType.getId());
            }
            inventoryProductRecordService.save(inventoryProductRecord);
        }

    }
    public void storageWorkPlanStatus(Long planId,String inoutTypeCode){
        if("production".equals(inoutTypeCode)){
            //判断入库单包装条码的数量是否大于或等于入库计划的送料数
            Map<Integer, Object> inoutSumMap = inventoryInoutJobDao.getInventoryInoutSum(planId);
            InventoryInoutVO inoutVO = inventoryInoutService.get4appById(planId);
            Integer planSum = Integer.valueOf(inoutSumMap.get("planSum").toString());
            Integer total = Integer.valueOf(inoutSumMap.get("total").toString());
            InventoryInout inventoryInout = new InventoryInout();
            CopyOptions copyOptions = CopyOptions.create()
                    .setEditable(InventoryInout.class)
                    .setIgnoreError(true)
                    .setIgnoreNullValue(true);
            BeanUtil.copyProperties(inoutVO, inventoryInout, copyOptions);
            if(planSum >= total){
                inventoryInout.setStatus(InventoryInout.Status.storage);
            }/*else if(planSum > 0){
                inventoryInout.setStatus(InventoryInout.Status.storagein);
            }*/
            inventoryInoutService.updateById(inventoryInout);
        }else if("purchase".equals(inoutTypeCode)){
            //判断入库单包装条码的数量是否大于或等于采购计划的采购数
            Map<Integer, Object> purchaseSumMap = inventoryInoutJobDao.getPurchaseSum(planId);
            PurchaseVO purchaseVO = purchaseService.get4appById(planId);
            Integer purchaseSum = Integer.valueOf(purchaseSumMap.get("planSum").toString());
            Integer total = Integer.valueOf(purchaseSumMap.get("total").toString());
            Purchase purchase = new Purchase();
            CopyOptions copyOptions = CopyOptions.create()
                    .setEditable(Purchase.class)
                    .setIgnoreError(true)
                    .setIgnoreNullValue(true);
            BeanUtil.copyProperties(purchaseVO, purchase, copyOptions);
            if(purchaseSum >= total){
                purchase.setStatus(Purchase.Status.isStock);
            }else if(purchaseSum > 0){
                purchase.setStatus(Purchase.Status.inStock);
            }
            purchaseService.updateById(purchase);
        }

    }
    @Override
    public List<InventoryJobLabelVO> getStoragePackLabel(Long jobId) {
        return inventoryJobLabelDao.getStoragePackLabel(jobId);
    }

    @Transactional
    @Override
    public void addOutWork(InventoryInoutJobVO inventoryInoutJobVO) {
        String enterpriseCode=JwtUtils.getEnterpriseCode();
        if (inventoryInoutJobVO == null) {
            throw new BusinessException("添加入库作业参数异常");
        }
        List<InventoryJobProductVO> productVOList = inventoryInoutJobVO.getDetailList();
        if (CollectionUtils.isEmpty(productVOList)) {
            throw new BusinessException("出库作业产品参数异常");
        }
        List<InventoryJobLabelVO> jobLabelList = inventoryInoutJobVO.getJobLabelList();
        if (CollectionUtils.isEmpty(jobLabelList)) {
            throw new BusinessException("包装条码参数异常");
        }

        String loginUsername = JwtUtils.getLoginUsername();
        String today = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
        String enterpriseId = String.valueOf(JwtUtils.getEnterpriseId());
        //查询出库计划
        InventoryOutPlanVO outPlanVO = inventoryOutPlanDao.get4appById(inventoryInoutJobVO.getPlanId());
        //查询出库计划类型
        LambdaQueryWrapper<WarehouseInventoryType> typeWrapper = new LambdaQueryWrapper<>();
        typeWrapper.eq(WarehouseInventoryType::getCode, outPlanVO.getInoutTypeCode());
        WarehouseInventoryType inventoryType = warehouseInventoryTypeService.getOne(typeWrapper);
        //出库作业单
        InventoryInoutJob inventoryInoutJob = new InventoryInoutJob();
        Integer maxCode = dynamicDao.getDayMaxNo("ord_inventory_inout_job");
        String code = CodeUtil.getCode(maxCode);
        //inventoryInoutJob.setCode(outPlanVO.getCode() + today + code);
        inventoryInoutJob.setCode("CK" + today + code);
        inventoryInoutJob.setPlanId(outPlanVO.getId());
        inventoryInoutJob.setPlanCode(outPlanVO.getCode());
        inventoryInoutJob.setInoutType(InventoryInoutJob.InoutType.out);
        inventoryInoutJob.setRemark(inventoryInoutJobVO.getRemark());
        inventoryInoutJob.setNo(Integer.valueOf(code));
        inventoryInoutJob.setDay(Integer.valueOf(today));
        inventoryInoutJob.setCreatorName(loginUsername);
        inventoryInoutJob.setInoutTypeCode(inventoryType.getCode());
        inventoryInoutJob.setInoutTypeName(inventoryType.getName());
        inventoryInoutJobDao.insert(inventoryInoutJob);
        //出库作业扩展
        InventoryJob inventoryJob = new InventoryJob();
        if(inventoryInoutJobVO.getInWarehouseId() != null){
            if (inventoryType.getCode().equals("allotCloudWarehouse")) {
                JsonResult<com.wing.platform.order.model.response.WarehouseVO> areaJsonResult = platformClient.getWarehouseById(inventoryInoutJobVO.getInWarehouseId());
                inventoryJob.setInAreaName(areaJsonResult.getData().getAddr());
            } else {
                WarehouseVO warehouseVO = warehouseDao.get4appById(inventoryInoutJobVO.getInWarehouseId());
                inventoryJob.setInAreaName(warehouseVO.getAddr());
            }
        }
        inventoryJob.setPlanId(outPlanVO.getId());
        inventoryJob.setJobId(inventoryInoutJob.getId());
        inventoryJob.setInoutType(InventoryJob.InoutType.out);
        inventoryJob.setCustomerName(inventoryInoutJobVO.getCustomerName());
        inventoryJob.setCustomerConcat(inventoryInoutJobVO.getCustomerConcat());
        inventoryJob.setCustomerMoble(inventoryInoutJobVO.getCustomerMoble());
        inventoryJob.setCarNo(inventoryInoutJobVO.getCarNo());
        inventoryJob.setExpressCode(inventoryInoutJobVO.getExpressCode());
        inventoryJob.setCompanyId(inventoryInoutJobVO.getCompanyId());
        inventoryJob.setTransportType(inventoryInoutJobVO.getTransportType());
        //目标仓的省市
        inventoryJob.setProvince(inventoryInoutJobVO.getProvince());
        inventoryJob.setCity(inventoryInoutJobVO.getCity());
        //出库作业目标仓存储
        inventoryJob.setInWarehouseId(inventoryInoutJobVO.getInWarehouseId());
        inventoryJob.setInWarehouseName(inventoryInoutJobVO.getInWarehouseName());
        inventoryJobDao.insert(inventoryJob);
        //出库作业单的产品明细
        Long warehouseId = null;
        for (InventoryJobProductVO item : productVOList) {
            if (item.getQuantityOut() > 0) {
                Long quantityOut = item.getQuantityOut();
                //减少出库计划详情的出库数量
                 InventoryOutPlanDetail outPlanDetail = inventoryOutPlanDetailService.getById(item.getId());
            if (outPlanDetail != null) {
                if (item.getQuantityOut() > outPlanDetail.getQuantity()) {
                    throw new BusinessException("sku编号为：" + outPlanDetail.getSkuCode() + "的出库数量不能大于计划出库数");
                }
                outPlanDetail.setQuantity(outPlanDetail.getQuantity() - item.getQuantityOut());
                inventoryOutPlanDetailDao.updateById(outPlanDetail);
            }
            String skuCode = item.getSkuCode();
            item.setId(null);
            InventoryJobProduct inventoryJobProduct = new InventoryJobProduct();
            inventoryJobProduct.setJobId(inventoryInoutJob.getId());
            inventoryJobProduct.setTotal(item.getSupplyPrice());
            inventoryJobProduct.setQuantity(item.getQuantityOut());
            inventoryJobProduct.setInoutType(InventoryJobProduct.InoutType.out);
            CopyOptions copyOptions = CopyOptions.create()
                    .setEditable(InventoryJobProduct.class)
                    .setIgnoreError(true)
                    .setIgnoreNullValue(true);
            BeanUtil.copyProperties(item, inventoryJobProduct, copyOptions);
            inventoryJobProductDao.insert(inventoryJobProduct);
            //出库作业单的包装码明细
            for (InventoryJobLabelVO jobLabelItem : jobLabelList) {
                if (skuCode.equals(jobLabelItem.getSkuCode())) {
                    //查询料箱
                    PalletBoxListVO palletBox = palletBoxListDao.getPalletBox(jobLabelItem.getBoxCode(),null);
                    if (palletBox == null) {
                        throw new BusinessException("料箱不存在");
                    }
                    //作业单条码记录
                    InventoryJobLabel jobLabel = new InventoryJobLabel();
                    jobLabel.setJobId(inventoryInoutJob.getId());
                    jobLabel.setJobProductId(inventoryJobProduct.getId());
                    jobLabel.setPlanId(outPlanVO.getId());
                    jobLabel.setPackLabeId(jobLabelItem.getPackLabeId());
                    jobLabel.setPackLabeCode(jobLabelItem.getCode());
                    jobLabel.setPackId(jobLabelItem.getPackId());
                    jobLabel.setPackName(jobLabelItem.getPackName());
                    jobLabel.setQuantity(jobLabelItem.getQuantity());
                    jobLabel.setStorageQuantity(jobLabelItem.getQuantityOut());
                    jobLabel.setInoutType(InventoryJobLabel.InoutType.out);
                    jobLabel.setStatus(InventoryJobLabel.Status.inventoryOut);
                    jobLabel.setBoxId(palletBox.getBoxId());
                    jobLabel.setWarehouseId(palletBox.getWarehouseId());
                    jobLabel.setAreaId(palletBox.getAreaId());
                    jobLabel.setShelfId(palletBox.getShelfId());
                    jobLabel.setSpaceId(palletBox.getSpaceId());
                    inventoryJobLabelDao.insert(jobLabel);
                    //将包装条码从料箱出库
                    ProductPackLabel packLabel = productPackLabelService.getById(jobLabel.getPackLabeId());
                    warehouseId = packLabel.getWarehouseId();
                    /*packLabel.setBoxId(null);
                    packLabel.setWarehouseId(null);
                    packLabel.setAreaId(null);
                    packLabel.setShelfId(null);
                    packLabel.setSpaceId(null);
                    productPackLabelService.updateById(packLabel);*/
                    //删除料箱存储包装编码
                    QueryWrapper<BoxLabel> wrapper = new QueryWrapper<>();
                    wrapper.eq("pack_labe_id", jobLabel.getPackLabeId());
                    BoxLabel boxLabel = boxLabelDao.selectOne(wrapper);
                    if (boxLabel != null) {
                        boxLabelDao.deleteById(boxLabel.getId());
                    }
                    //出库包装条码调用的接口
                    com.wing.product.model.request.ProductPackLabelForm productPackLabelForm = productPackLabelService.extractLabel4InventoryOut(jobLabel.getPackLabeCode(),
                            jobLabelItem.getQuantityOut().intValue(), 1);
                    if(jobLabelItem.getQuantityOut().intValue() != packLabel.getQuantity()){
                        //返回的新条码
                        BoxLabel newBoxLabel = new BoxLabel().builder()
                                .packLabeCode(productPackLabelForm.getCode())
                                .packLabeId(productPackLabelForm.getId())
                                .quantity(productPackLabelForm.getQuantity().longValue())
                                .packLabeQuantity(productPackLabelForm.getQuantity().longValue())
                                .boxId(boxLabel.getBoxId())
                                .skuCode(boxLabel.getSkuCode())
                                .packName(boxLabel.getPackName())
                                .warehouseId(boxLabel.getWarehouseId())
                                .areaId(boxLabel.getAreaId())
                                .shelfId(boxLabel.getShelfId())
                                .spaceId(boxLabel.getSpaceId())
                                .build();
                        boxLabelDao.insert(newBoxLabel);
                    }
                }

            }
                //扣减库存和库存变动
                //查询是否有库存数据
                com.wing.order.model.entity.CabInventoryProduct cabInventory = cabInventoryProductService.getInventoryProductVOBySkuCode(skuCode, warehouseId, 0);
                com.wing.order.model.entity.CabInventoryProductRecord inventoryProductRecord = new com.wing.order.model.entity.CabInventoryProductRecord();
                if (cabInventory == null) {
                    throw new BusinessException("SKU[" + skuCode + "]产品还未入库");
                } else {
                    if (quantityOut > cabInventory.getQuantity()) {
                        //出库数大于库存数
                        throw new BusinessException("SKU[" + skuCode + "]产品出库数大于库存数");
                    } else {
                        //库存变动记录的值
                        inventoryProductRecord.setInventoryProductId(cabInventory.getId());
                        inventoryProductRecord.setQuantityCurrent(cabInventory.getQuantity());//当前库存
                        inventoryProductRecord.setQuantityAfter((int) (cabInventory.getQuantity() - quantityOut));//变动后库存
                        //库存变动
                        cabInventory.setQuantity((int) (cabInventory.getQuantity() - quantityOut));
                        cabInventoryProductService.updateById(cabInventory);
                        //库存变动记录
                        inventoryProductRecord.setPlanId(outPlanVO.getId());
                        inventoryProductRecord.setJobId(inventoryInoutJob.getId());
                        inventoryProductRecord.setSkuCode(skuCode);
                        inventoryProductRecord.setType(com.wing.order.model.entity.CabInventoryProductRecord.Type.out);
                        WarehouseInventoryType warehouseInventoryType = warehouseInventoryTypeService.getOne(new QueryWrapper<WarehouseInventoryType>().eq("code", "QT_CK"));
                        if(null != warehouseInventoryType){
                            inventoryProductRecord.setWarehouseInventoryTypeId(warehouseInventoryType.getId());
                        }
                        inventoryProductRecordService.save(inventoryProductRecord);
                    }
                }
                //查询出库计划产品的出库计划总数
                Integer planSum = inventoryOutPlanDao.getInventoryOutPlanSum(outPlanVO.getId());
                //等于0 代表出库计划产品的计划出库数全部为0
                if(planSum == 0){
                    InventoryOutPlan inventoryOutPlan = new InventoryOutPlan();
                    CopyOptions copyOptions2 = CopyOptions.create()
                            .setEditable(InventoryOutPlan.class)
                            .setIgnoreError(true)
                            .setIgnoreNullValue(true);
                    BeanUtil.copyProperties(outPlanVO, inventoryOutPlan,copyOptions2);
                    inventoryOutPlan.setStatus(InventoryOutPlan.Status.fulfill);
                    inventoryOutPlanDao.updateById(inventoryOutPlan);
                }
        }
    }
        //出库类型是调拨到云仓才同步数据
        if (inventoryType.getCode().equals("allotCloudWarehouse")){
            //同步平台数据
            List<InventoryInoutPlanDetailForm> planProductList = new ArrayList<>();
            BigDecimal totalAmount = BigDecimal.ZERO;
            for (InventoryJobProductVO item :productVOList){
                InventoryInoutPlanDetailForm detailForm = new InventoryInoutPlanDetailForm();
                detailForm.setSpPrice(item.getSupplyPrice())
                        .setQuantity(item.getQuantityOut().intValue())
                        .setSkuName(item.getProductName())
                        .setProductPic(item.getSkuPic())
                        .setSkuCode(item.getSkuCode())
                        .setSkuSpecValueNames(item.getSkuSpecCode());
                planProductList.add(detailForm);

                BigDecimal amount = new BigDecimal(item.getQuantityOut()).multiply(item.getSupplyPrice());
                totalAmount = totalAmount.add(amount);
            }

            InventoryInoutPlanForm inventoryInoutPlanForm = new InventoryInoutPlanForm();
            inventoryInoutPlanForm.setEnterpriseCode(enterpriseCode);
            inventoryInoutPlanForm.setWarehouseInventoryTypeCode("RK02");
            inventoryInoutPlanForm.setInventoryTypeOrderCode("CK" + today + code);
            long sum = planProductList.stream().filter(x -> x.getQuantity() != null).mapToLong(x -> x.getQuantity()).sum();
           /* planProductList.stream().filter(x -> x.getSupplyPrice() != null)
            .map(aa -> aa.getSupplyPrice().multiply(new BigDecimal(aa.getQuantity()))).reduce(BigDecimal.ZERO, BigDecimal::add);*/
            inventoryInoutPlanForm.setTotalQuantity((int) sum);
            inventoryInoutPlanForm.setTotalAmount(totalAmount);
            inventoryInoutPlanForm.setDetailList(planProductList);
            /*inventoryInoutJobVO.setCode(enterpriseCode + "_" + inventoryInoutJob.getCode());
            inventoryInoutJobVO.setEnterpriseCode(enterpriseCode);
            inventoryInoutJobVO.setLoginUsername(loginUsername);
            inventoryInoutJobVO.setEnterpriseId(Long.parseLong(enterpriseId));
            //查询出库仓数据 出库仓
            WarehouseVO warehouseVO = warehouseDao.get4appById(outPlanVO.getOutWarehouseId());
            inventoryInoutJobVO.setOutWarehouseName(warehouseVO.getName());
            //查询出库的物流公司
            JsonResult<TransportCompany> companyJson = enterpriseClient.getTransportCompanyById(inventoryInoutJobVO.getCompanyId());
            inventoryInoutJobVO.setLogisticsCompany(companyJson.getData().getName());
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            inventoryInoutJobVO.setSendTimeStr(df.format(outPlanVO.getSendTime()));
            //查询当前登录信息
            JsonResult<UserVO> userInfo = userClient.getUserInfo(JwtUtils.getLoginUserId());
            if (userInfo.getCode() == Result.Code.SUCCESS.getCode()) {
                inventoryInoutJobVO.setConsignerMobel(userInfo.getData().getPhone());
            }
            //同步到平台端
            //String jsonObject = JSONUtil.toJsonStr(inventoryJobForm);
            com.wing.platform.order.model.response.InventoryInoutJobVO inventoryInoutJobVO1 = new com.wing.platform.order.model.response.InventoryInoutJobVO();
            CopyOptions copyOptions = CopyOptions.create()
                    .setEditable(InventoryJobProduct.class)
                    .setIgnoreError(true)
                    .setIgnoreNullValue(true);
            BeanUtil.copyProperties(inventoryInoutJobVO, inventoryInoutJobVO1);*/
            JsonResult addOutResult = platformClient.syncCloudStoragePlan(inventoryInoutPlanForm);
            if (addOutResult.getCode() != Result.Code.SUCCESS.getCode()) {
                throw new BusinessException("同步到平台异常" + addOutResult.getMsg());
            }
        }
    }

    private Long getSumQuantity(List<OrderDeliveryLabelVO> labels){
        Long sum=0l;
        for (OrderDeliveryLabelVO item:labels){
            sum+=item.getQuantityInOut();
        }
        return sum;
    }

}
